﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class AppInit : MonoBehaviour {

    public const string CostTimeKeyPre = "history_cost_time_";
    public const string CountKeyPre = "history_count_";
    public const string CalcCountModeKey = "calc_count_mode_key";

    public GameObject startPanel;
    public GameObject countPanel;
    public GameObject historyPanel;
    public GameObject historySVCellItem;
    public AudioSource audioSource;
    public GameObject gitImage1;
    public GameObject gitImage2;

    private int gitImageIndex = 0;
    private int midCount = 0;
    private int leftCount = 0;
    private int rightCount = 0;
    private DateTime startTime;
    private DateTime stopTime;

    private Text nowTimeLab = null;


    void Awake()
    {
        EnterStartScene();

#if UNITY_EDITOR
        PlayerPrefs.DeleteAll();
#endif
    }

    public void EnterStartScene()
    {
        startPanel.SetActive(true);
        countPanel.SetActive(false);
        historyPanel.SetActive(false);
        
        AddListener(startPanel,"StartButton",() =>
        {
            EnterCountScene();
        });

        AddListener(startPanel,"HistoryButton", () =>
        {
            EnterHistoryScene();
        });

        AddListener(startPanel,"ExitButton", () =>
        {
            Application.Quit();
        });

        StopAllCoroutines();
        StartCoroutine(PlayGitImage());

    }

    private IEnumerator PlayGitImage()
    {
        gitImageIndex = 0;
        while (true)
        {
            var isShow1 = gitImageIndex == 0;
            gitImage1.SetActive(isShow1);
            gitImage2.SetActive(!isShow1);
            gitImageIndex = (gitImageIndex + 1) % 2;
            yield return new WaitForSeconds(0.1f);
        }
    }

    public void EnterCountScene()
    {
        startPanel.SetActive(false);
        countPanel.SetActive(true);
        historyPanel.SetActive(false);

        var timeLab = countPanel.transform.Find("TimeLab").GetComponent<Text>();
        nowTimeLab = countPanel.transform.Find("nowTimeLab").GetComponent<Text>();
        var singleSide = countPanel.transform.Find("SingleSide").gameObject;
        var doubleSide = countPanel.transform.Find("DoubleSide").gameObject;
        var switchBtnGo = countPanel.transform.Find("SwitchButton").gameObject;
        var leftCountLab = countPanel.transform.Find("DoubleSide/LeftCountLab").GetComponent<Text>();
        var rightCountLab = countPanel.transform.Find("DoubleSide/RightCountLab").GetComponent<Text>();
        var midCountLab = countPanel.transform.Find("SingleSide/CountLab").GetComponent<Text>();
        
        AddListener(countPanel, "DoubleSide/LeftAddButton", () =>
        {
            switchBtnGo.SetActive(false);
            ++leftCount;
            leftCountLab.text = leftCount.ToString();
        });
        AddListener(countPanel, "DoubleSide/RightAddButton", () =>
        {
            switchBtnGo.SetActive(false);
            ++rightCount;
            rightCountLab.text = rightCount.ToString();
        });
        AddListener(countPanel, "SingleSide/AddButton", () =>
        {
            switchBtnGo.SetActive(false);
            ++midCount;
            midCountLab.text = midCount.ToString();
        });

        AddListener(countPanel, "SwitchButton", () =>
        {
            var curMode = PlayerPrefs.GetInt(CalcCountModeKey,0);
            curMode = (curMode + 1) % 2;

            var isModelSingel = curMode == 0;
            singleSide.SetActive(isModelSingel);
            doubleSide.SetActive(!isModelSingel);

            PlayerPrefs.SetInt(CalcCountModeKey, curMode);
        });

        AddListener(countPanel,"StopButton",() =>
        {
            StopAllCoroutines();
            stopTime = System.DateTime.Now;
            var curMode = PlayerPrefs.GetInt(CalcCountModeKey,0); 
            if (curMode == 0)
            {
                SaveCount(startTime, stopTime, midCount, 0, curMode);
            }
            if (curMode == 1)
            {
                SaveCount(startTime, stopTime, leftCount, rightCount, curMode);
            }
            EnterStartScene();
        });

        leftCountLab.text = "0";
        rightCountLab.text = "0";
        midCountLab.text = "0";
        leftCount = 0;
        rightCount = 0;
        midCount = 0;
        startTime = System.DateTime.Now;
        timeLab.text = startTime.ToString("T");
        switchBtnGo.SetActive(true);

        var _curMode = PlayerPrefs.GetInt(CalcCountModeKey,0);
        var _isModelSingel = _curMode == 0;
        singleSide.SetActive(_isModelSingel);
        doubleSide.SetActive(!_isModelSingel);

        StopAllCoroutines();
        StartCoroutine(ShowRunTime());
    }

    public IEnumerator ShowRunTime()
    {
        while (true)
        {
            nowTimeLab.text = System.DateTime.Now.ToString("T");
            yield return new WaitForSeconds(1f);
        }
    }

    public void EnterHistoryScene()
    {
        startPanel.SetActive(false);
        countPanel.SetActive(false);
        historyPanel.SetActive(true);
        historySVCellItem.SetActive(false);

        AddListener(historyPanel,"ReturnButton", () =>
        {
            EnterStartScene();
        });

        AddListener(historyPanel,"ClearButton", () =>
        {
            PlayerPrefs.DeleteAll();
            EnterHistoryScene();
        });

        var contentTran = historyPanel.transform.Find("ScrollView/Viewport/Content");
        var childCount = contentTran.childCount;
        for (int index = 0; index < childCount; index++)
        {
            var child = contentTran.GetChild(0);
            if (child != null)
            {
                child.gameObject.SetActive(false);
                child.SetParent(null);
                GameObject.Destroy(child.gameObject);
            }
        }

        var i = 1;
        while (PlayerPrefs.HasKey(CostTimeKeyPre + i.ToString()))
        {
            var timeStr = PlayerPrefs.GetString(CostTimeKeyPre + i.ToString());
            var countStr = PlayerPrefs.GetString(CountKeyPre + i.ToString());

            var cellItem = GameObject.Instantiate<GameObject>(historySVCellItem);
            var timeLab = cellItem.transform.Find("timeLab").GetComponent<Text>();
            timeLab.text = timeStr;

            var countLab = cellItem.transform.Find("countLab").GetComponent<Text>();
            countLab.text = "人数: " + countStr;

            cellItem.transform.SetParent(contentTran);
            cellItem.transform.localScale = Vector3.one;
            cellItem.transform.localPosition = Vector3.zero;
            cellItem.SetActive(true);

            ++i;
        }
    }



    private void SaveCount(DateTime start, DateTime end, int leftCount,int rightCount,int mode)
    {
        var i = 1;
        while (PlayerPrefs.HasKey(CostTimeKeyPre + i.ToString()))
        {
            ++i;
        }
        var min = (int)(end.Subtract(start).TotalMinutes);
        var costMin = (int)Math.Ceiling(end.Subtract(start).TotalMinutes);
        var timeStr = start.Month + "月" + start.Day + "日" + " " + start.ToString("t") + " - " + end.ToString("t") + "  耗时: " + costMin + "分";
        if (mode == 0)
        {
            if (min <= 0 && leftCount <= 0)
            {
                return;
            }
            PlayerPrefs.SetString(CostTimeKeyPre + i.ToString(), timeStr);
            PlayerPrefs.SetString(CountKeyPre + i.ToString(), leftCount.ToString());
        }
        if (mode == 1)
        {
            if (min <= 0 && (leftCount <= 0 && rightCount <= 0))
            {
                return;
            }
            PlayerPrefs.SetString(CostTimeKeyPre + i.ToString(), timeStr);
            PlayerPrefs.SetString(CountKeyPre + i.ToString(), "左：" + leftCount.ToString() + ", 右：" + rightCount.ToString());
        }
       
    }

    private void AddListener(GameObject parentGo, string btnPath, UnityAction action)
    {
        var btnTrans = parentGo.transform.Find(btnPath);
        var btn = btnTrans.GetComponent<Button>();
        btn.onClick.RemoveAllListeners();
        btn.onClick.AddListener(()=>{
            audioSource.Play();
            action();
        });
    }
}
